/*
 * @Version: 0.0.1
 * @Author: ider
 * @Date: 2021-02-07 17:13:20
 * @LastEditors: ider
 * @LastEditTime: 2021-06-09 08:30:24
 * @Description: 实现负载均衡
 */
package rpc

import (
	"context"
	"fmt"
	"historyOfWikipedia/pb/wikitext_pb"
	"sync/atomic"

	log "github.com/sirupsen/logrus"

	"google.golang.org/grpc"
)

var (
	ctx = context.Background()
)

type RemoteWikiTextServer struct {
	conns   []*grpc.ClientConn
	clients []*wikitext_pb.WikiTextPlainServiceClient
	current uint64
}

func NewRemoteWikiTextServer() *RemoteWikiTextServer {
	rgt := RemoteWikiTextServer{}

	serverCount := 10
	basicPort := 11120
	for i := 0; i < serverCount; i++ {
		conn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%d", basicPort+i), grpc.WithInsecure())
		if err != nil {
			log.Fatal(err)
		}
		client := wikitext_pb.NewWikiTextPlainServiceClient(conn)
		rgt.clients = append(rgt.clients, &client)
		rgt.conns = append(rgt.conns, conn)
	}

	return &rgt
}

func (c *RemoteWikiTextServer) ShortestDistance(text string) int32 {

	// 通过编译rpc.pb.go得到NewHelloServiceClient函数来处理连接

	// 通过编译rpc.pb.go得到的Hello服务来发送数据类型为String的数据
	// edges := []*pb.Edge{{SourceID: 1, TargetID: 2}, {SourceID: 2, TargetID: 3}}
	// for i := 0; i < 10000; i++ {
	// 	edges = append(edges, &pb.Edge{SourceID: int64(i), TargetID: int64(i + 1)})
	// }
	idx := int(atomic.AddUint64(&c.current, uint64(1)) % uint64(len(c.clients)))
	obj, err := (*c.clients[idx]).GetWikiTextPlain(ctx, &wikitext_pb.Wiki_Text{Text: text})
	if err != nil {
		log.Fatal(err, obj)
	}

	return int32(obj.Count)
}

func (c *RemoteWikiTextServer) Close() {
	for _, conn := range c.conns {
		conn.Close()
	}
}
